<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="广告位置" prop="positionId">
        <el-select
          v-model="queryParams.positionId"
          placeholder="广告位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in positionOptions"
            :key="item.positionId"
            :label="item.name"
            :value="item.positionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="帐号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择帐号状态" clearable size="small">
          <el-option label="显示" value="0" />
          <el-option label="隐藏" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:adver:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:adver:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:adver:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:adver:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-location-outline"
          size="mini"
          @click="handlePosition"
          v-hasPermi="['monitor:job:edit']"
        >位置
        </el-button>
        <Position ref="position" />
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="adverList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55"  />
      <el-table-column label="广告编号" align="center" prop="adverId" width="100"/>
      <el-table-column label="标题" align="center" prop="title" width="300"/>
      <el-table-column label="广告位置" align="center" prop="positionName" width="100"/>
      <el-table-column label="形式" align="center" prop="mediaType" width="50"/>
      <el-table-column label="广告图片" align="center"  prop="adverImg" >
        <template slot-scope="{row}">
          <el-image
            class="adver-image"
            :src="row.adverImg"
            :preview-src-list="[row.adverImg]"
            fit="contain"
            lazy
          >
            <div slot="error">
              <i class="el-icon-document" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="跳转类型" align="center" prop="adverTypeName" width="100"/>
      <el-table-column label="跳转地址" align="center" prop="adverHref" />
      <el-table-column label="帐号状态" align="center" prop="status" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.status == '0'" >显示</el-tag>
          <el-tag v-if="row.status == '1'" type="info">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:adver:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:adver:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告位置" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择">
            <el-option
              v-for="item in positionOptions"
              :key="item.positionId"
              :label="item.name"
              :value="item.positionId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="形式">
          <el-radio-group v-model="form.mediaType">
            <el-radio
              v-for="item in mediaTypeList"
              :key="item"
              :label="item"
            >{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="跳转类型" prop="adverType">
          <el-select v-model="form.adverType" placeholder="请选择跳转类型">
            <el-option
              v-for="item in adverTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="跳转地址" prop="adverHref">
          <el-input v-model="form.adverHref" placeholder="请输入跳转地址" />
        </el-form-item>
        <el-form-item label="图片地址" prop="adverImg">
          <el-upload
            :action="commonUploadApi"
            :accept="'.png,.jpg'"
            :file-list="fileList"
            :headers="headers"
            :before-remove="handleBeforeRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :limit="1"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="帐号状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in visibleOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Position from './position'
import { listAdver, getAdver, delAdver, addAdver, updateAdver, exportAdver } from "@/api/system/adver/adver";
import { listPosition } from "@/api/system/adver/position";
import {mapGetters} from "vuex";
import { getToken } from "@/utils/auth";
export default {
  components: { Position },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 广告管理表格数据
      adverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        positionId: undefined,
        mediaType: undefined,
        title: undefined,
        adverImg: undefined,
        adverHref: undefined,
        adverType: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        positionId: [
          { required: true, message: "广告位置不能为空", trigger: "blur" }
        ],
        mediaType: [
          { required: true, message: "形式不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        adverImg: [
          { required: true, message: "图片地址不能为空", trigger: "blur" }
        ],
        adverType: [
          { required: true, message: "跳转类型", trigger: "blur" }
        ],
        status: [
          { required: true, message: "帐号状态（0正常 1停用）不能为空", trigger: "blur" }
        ],
      },
      positionOptions: [],
      visibleOptions: [],
      adverTypeOptions: [],
      mediaTypeList: [
        1,2,3,4,5
      ],
      fileList: [],
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  computed: {
    ...mapGetters([
      'commonUploadApi',
      'baseApi'
    ])
  },
  created() {
    this.getList();
    this.getPosition();

    this.getDicts("sys_show_hide").then(response => {
      this.visibleOptions = response;
    });

    this.getDicts("sys_adver_type").then(response => {
      this.adverTypeOptions = response;
    });
  },
  methods: {
    /** 查询广告管理列表 */
    getList() {
      this.loading = true;
      listAdver(this.queryParams).then(response => {
        this.adverList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getPosition(){
      listPosition({ pageNum: 1, pageSize: 1000}).then(response => {
        this.positionOptions = response.rows
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        adverId: undefined,
        positionId: undefined,
        mediaType: 1,
        title: undefined,
        adverImg: undefined,
        adverHref: undefined,
        adverType: '1',
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.adverId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const adverId = row.adverId || this.ids
      getAdver(adverId).then(response => {
        this.form = response;
        this.fileList.push({ url:response.adverImg });
        this.open = true;
        this.title = "修改广告管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.adverId != undefined) {
            updateAdver(this.form).then(response => {
               this.msgSuccess("修改成功");
               this.open = false;
               this.getList();
            });
          } else {
            addAdver(this.form).then(response => {
               this.msgSuccess("新增成功");
               this.open = false;
               this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const adverIds = row.adverId || this.ids;
      this.$confirm('是否确认删除广告管理编号为"' + adverIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAdver(adverIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有广告管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportAdver(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handlePosition(){
      this.$refs["position"].positionOpen = true;
      this.$refs["position"].handleInit();
    },
    handleSuccess(response, file, fileList){
      this.form.adverImg = response.url;
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.msgError(msg.message);
    },
    handleBeforeRemove(file, fileList) {
      this.form.adverImg = null;
    },
  }
};
</script>
<style >
  .adver-image>img{
    width: 100%;
    height: 120px;
  }
</style>
